package com.bms.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.bms.dao.BookDao;
import com.bms.entity.Book;
import com.google.gson.Gson;

public class BookAction extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");
		BookDao dao = new BookDao();
		if ("checkIsbn".equals(method)) {
			// 1、获取输入的ISBN-->books表主键
			String isbn = request.getParameter("isbn");
			// 2、查询数据库
			boolean flag = dao.checkIsbn(isbn);
			// 封装检测的结果
			Map<String, Boolean> result = new HashMap<String, Boolean>();
			result.put("flag", flag);

			Gson gson = new Gson();
			// result--->{"flag":true}
			String str = gson.toJson(result);
			// 3、返回检测的结果
			// 设置返回的数据的类型--->json类型的数据
			response.setContentType("application/json;charset=utf-8");
			// 输出流--->输出一些信息
			PrintWriter writer = response.getWriter();
			// 将数据放到缓冲区
			writer.write(str);
			// 刷新缓冲区的数据--->缓冲区的数据输出
			writer.flush();
		} else if ("add".equals(method)) {
			Book book = getBookInfo(request);
			dao.insert(book);

			response.sendRedirect("books/index.jsp");
		} else if ("delete".equals(method)) {// 删除
			String isbn = request.getParameter("isbn");
			dao.delete(isbn);
			response.sendRedirect("books/index.jsp");
		} else if ("doEdit".equals(method)) {// 更新
			Book book = getBookInfo(request);
			dao.update(book);
			response.sendRedirect("books/index.jsp");
		} else if ("search".equals(method)) {// 查询
			String isbn = request.getParameter("isbn");
			String name = request.getParameter("name");
			Map<String, Object> param = new HashMap<String, Object>();
			if (StringUtils.isNotBlank(isbn)) {
				param.put("b.ISBN", isbn);
			}
			if (StringUtils.isNotBlank(name)) {
				param.put("b.name", name);
			}

			List<Book> list = dao.queryAll(param);
			request.setAttribute("list", list);

			request.getRequestDispatcher("bookQuery/index.jsp").forward(
					request, response);
		}
	}

	private Book getBookInfo(HttpServletRequest request) {
		try {
			// 1、获取图书的信息
			String isbn = request.getParameter("isbn");
			String name = request.getParameter("name");

			String publisherIdParam = request.getParameter("publisherId");
			int publisherId = Integer.valueOf(publisherIdParam);

			String priceParam = request.getParameter("price");
			float price = Float.valueOf(priceParam);

			String publishTimeParam = request.getParameter("publishTime");
			SimpleDateFormat format = new SimpleDateFormat("yyyy");
			// 转正Java.util.date类型数据
			java.util.Date date = format.parse(publishTimeParam);
			Date publishTime = new Date(date.getTime());

			String versionParam = request.getParameter("version");
			int version = Integer.valueOf(versionParam);

			String[] authorIdsParam = request.getParameterValues("authorIds");
			int[] authorIds = strArray2IntArray(authorIdsParam);
			// 2、调用dao里面insert保存

			Book book = new Book();
			book.setIsbn(isbn);
			book.setName(name);
			book.setPrice(price);
			book.setPublisherId(publisherId);
			book.setPublishTime(publishTime);
			book.setVersion(version);
			book.setAuthorsId(authorIds);

			return book;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 将字符串数组转换成整型数组
	private int[] strArray2IntArray(String[] src) {
		if (src != null && src.length > 0) {
			int[] result = new int[src.length];
			for (int i = 0; i < src.length; i++) {
				result[i] = Integer.valueOf(src[i]);
			}
			return result;
		}
		return null;
	}

}
